package cn.cque.service.impl;

import cn.cque.dao.CategoryDao;
import cn.cque.dao.OrderDao;
import cn.cque.dao.OrderItemDao;
import cn.cque.entity.*;
import cn.cque.service.OrderService;
import cn.cque.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: XWC
 * @ClassName: OrderServiceImpl
 * @Date: 2020/10/5
 * @Time: 14:40
 * @Description:
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderDao orderDao;

    @Autowired
    OrderItemDao orderItemDao;


    @Override
    @Transactional
    public Order createOrder(User user, Cart cart) {
        //业务逻辑
        /*创建订单*/
        //生成订单ID
        String orderId = UUIDUtils.getId();
        //创建订单
        Date createTime = new Date();

        Order order = new Order();
        order.setId(orderId);
        order.setCreateTime(createTime);
        order.setTotal(cart.getTotalPrice());
        order.setState(OrderStatus.NON_PAYMENT.getCode());
        order.setUid(user.getId());
        orderDao.insert(order);

        //创建订单项
        List<CartItem> cartItemList = cart.getList();

        cartItemList.forEach(i -> {
            /*String itemId= UUIDUtils.getId();*/
            OrderItem orderItem = new OrderItem();
            orderItem.setId(UUIDUtils.getId());
            orderItem.setQuantity(i.getNum());
            orderItem.setTotal(i.getSumPrice());
            orderItem.setPid(i.getKey());
            orderItem.setOid(orderId);
            orderItemDao.insert(orderItem);

        });
        return findById(orderId);
    }

    @Override
    @Transactional
    public Integer updateOrder(Order order) {
        return orderDao.updateOrder(order);
    }

    @Override
    public List<Order> findAllByUid(String uid) {
        //查询订单ID列表信息
        List<Order> orderList = orderDao.findAllByUid(uid);

        //查询每个订单中的订单项封装到订单中
        return orderList.stream().map(o -> o.getId()).map(this::findById).collect(Collectors.toList());
    }

    @Override
    public Order findById(String id) {
        //查询订单信息
        Order order = orderDao.findById(id);

        //查询订单关联的订单项，再封装
        List<OrderItem> orderItemList = orderItemDao.findListByOid(order.getId());

        order.setOrderItemList(orderItemList);
        return order;
    }

    @Override
    public List<Order> findAll() {
        return orderDao.findAll();
    }

    @Override
    @Transactional
    public Integer deleteOrder(String id) {
        return orderDao.deleteOrder(id);
    }
}